<?php

namespace addons\booking\model;

use think\Model;


class Teasing extends Model
{


    // 表名
    protected $name = 'booking_teasing';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [];

    public function setTeasingConfigIdsAttr($value)
    {
        if (is_array($value)) {
            return join(',', $value);
        }
        return $value;
    }

    public function setImagesAttr($value)
    {
        if (is_array($value)) {
            return join(',', $value);
        }
        return $value;
    }

    public function getImagesAttr($value)
    {
        if (!empty($value)) {
            $data = explode(',', $value);
            foreach ($data as &$item) {
                $item = cdnurl($item, true);
            }
            return $data;
        }
        return [];
    }

    public function getTagNamesAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['tag_names']) ? $data['tag_names'] : '');
        if (!$value) {
            return [];
        }
        return explode(',', $value);
    }

    /**
     * 列表
     *
     * @param array $param
     * @return void
     */
    public static function tableList($param)
    {
        $pageNum = 15;
        if (isset($param['num']) && !empty($param['num'])) {
            $pageNum = $param['num'];
        }
        return self::with([
            'replay' => [
                'Manage' => function ($query) {
                    $query->field('id,nickname');
                }
            ]
        ])->field('t.id,t.pid,t.user_id,t.teasing_config_ids,t.content,t.images,t.createtime,GROUP_CONCAT(c.name) tag_names')
            ->where(function ($query) use ($param) {
                $query->where('pid', 0);
                if (isset($param['user_id']) && $param['user_id'] != '') {
                    $query->where('user_id', $param['user_id']);
                }
            })->alias('t')
            ->join('booking_config c', 'FIND_IN_SET(c.id,t.teasing_config_ids)', 'LEFT')
            ->order('createtime desc')
            ->group('t.id')
            ->paginate($pageNum);
    }

    public function replay()
    {
        return $this->hasMany('Teasing', 'pid', 'id', [], 'LEFT');
    }

    public function Manage()
    {
        return $this->belongsTo('\app\admin\model\Admin', 'user_id', 'id', [], 'LEFT');
    }

    public function User()
    {
        return $this->belongsTo('\app\common\model\User', 'user_id', 'id', [], 'LEFT');
    }
}
